package com.zr.influx.service;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.WriteApi;
import com.influxdb.client.domain.WritePrecision;
import com.zr.influx.model.ForexData;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * InfluxDB服务，负责将数据写入InfluxDB
 */
@Service
@RequiredArgsConstructor
public class InfluxDBService {

    private static final Logger logger = LoggerFactory.getLogger(InfluxDBService.class);

    @Autowired
    private InfluxDBClient influxDBClient;

    @Value("${influxdb.bucket}")
    private String bucket;

    @Value("${influxdb.org}")
    private String org;

    /**
     * 将单个外汇行情数据写入InfluxDB
     */
    public void writeForexData(ForexData forexData) {
        try (WriteApi writeApi = influxDBClient.getWriteApi()) {
            writeApi.writeMeasurement(bucket, org, WritePrecision.NS, forexData);
            logger.debug("成功写入数据: {} @ {}", forexData.getCurrencyPair(), forexData.getTimestamp());
        } catch (Exception e) {
            logger.error("写入InfluxDB失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 批量写入外汇行情数据到InfluxDB
     */
    public void batchWriteForexData(List<ForexData> forexDataList) {
        try (WriteApi writeApi = influxDBClient.getWriteApi()) {
            writeApi.writeMeasurements(bucket, org, WritePrecision.NS, forexDataList);
            logger.info("成功批量写入 {} 条数据", forexDataList.size());
        } catch (Exception e) {
            logger.error("批量写入InfluxDB失败: {}", e.getMessage(), e);
        }
    }
}

